from mitmproxy import http

# 路由配置字典：原始URL前缀 -> 目标路径
REDIRECT_MAPPINGS = {
    "https://personal-bus.wps.cn/activity/clock_in/v1/task/": {
        "base_path": "/cloud-api/dd/wps/",
        "keep_path": True
    },
    "https://personal-bus.wps.cn/activity/clock_in/v1/clock_in": {
        "base_path": "/cloud-api/dd/wps/wx-mini/clock_in",
        "keep_path": False
    },
    "https://personal-bus.wps.cn/activity/clock_in/v1/info": {
        "base_path": "/cloud-api/dd/wps/wx-mini/info",
        "keep_path": False
    },
    "https://personal-bus.wps.cn/activity/clock_in/v1/reward": {
        "base_path": "/cloud-api/dd/wps/wx-mini/reward",
        "keep_path": False
    },
    "https://vip.wps.cn/wx_adapter/v1/app/bind/user": {
        "base_path": "/cloud-api/dd/wps/finish_browse2",
        "keep_path": False
    },
    "https://account.wps.cn/api/user/agreement": {
        "base_path": "/cloud-api/dd/wps/easy_login",
        "keep_path": False
    },
    "https://account.wps.cn/passport/secure/api/easy_login": {
        "base_path": "/cloud-api/dd/wps/easy_login",
        "keep_path": False
    }
}


def request(flow: http.HTTPFlow) -> None:
  original_url = flow.request.pretty_url

  for prefix, config in REDIRECT_MAPPINGS.items():
    if original_url.startswith(prefix):
      if config["keep_path"]:
        keep_start = len(prefix)
        path_suffix = original_url[keep_start:]
        # 更安全的路径拼接
        base = config["base_path"].rstrip("/")
        suffix = path_suffix.lstrip("/")
        new_path = f"{base}/{suffix}" if suffix else base
      else:
        new_path = config["base_path"]

      # 修改请求
      flow.request.scheme = "https"
      flow.request.host = "ddy.sh.cn"
      flow.request.port = 443
      flow.request.path = new_path
      flow.request.headers["Host"] = "ddy.sh.cn"

      # 调试输出
      print(f"Redirected: {original_url} → https://ddy.sh.cn{new_path}")
      break
